//
//  KTitleTextCell.m
//  Keping
//
//  Created by 柯平 on 2017/6/30.
//  Copyright © 2017年 柯平. All rights reserved.
//

#import "KTitleTextCell.h"

@interface KTitleTextCell()<UITextFieldDelegate>

@end

@implementation KTitleTextCell

-(instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        
    }
    return self;
}

-(void)layoutSubviews
{
    [super layoutSubviews];
    
    [self.titleLb mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(10);
        make.top.bottom.mas_equalTo(0);
        make.width.mas_equalTo(kScreenWidth/2);
    }];
    [self.textTf mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(-10);
        make.left.mas_equalTo(100);
        make.bottom.top.mas_equalTo(0);
    }];
}

-(UILabel *)titleLb
{
    if (!_titleLb) {
        _titleLb = [UILabel new];
        [self.contentView addSubview:_titleLb];
    }
    return _titleLb;
}

-(UITextField *)textTf
{
    if (!_textTf) {
        _textTf = [UITextField new];
        [self.contentView addSubview:_textTf];
        _textTf.textAlignment = NSTextAlignmentRight;
        [_textTf addTarget:self action:@selector(replaceNormalSpaceUsingNonbreakingSpace) forControlEvents:UIControlEventEditingChanged];
        _textTf.borderStyle = UITextBorderStyleNone;
        _textTf.delegate = self;
        _textTf.returnKeyType =UIReturnKeyDone;
    }
    return _textTf;
}

// 在响应事件中将@" "替换为non-breaking space
- (void)replaceNormalSpaceUsingNonbreakingSpace
{
    UITextRange *textRange = self.textTf.selectedTextRange;
    self.textTf.text = [self.textTf.text stringByReplacingOccurrencesOfString:@" "
                                                     withString:@"\u00a0"];
    [self.textTf setSelectedTextRange:textRange];
}

- (void)textFieldDidEndEditing:(UITextField *)textField {
    if (self.CommunityForText) {
        self.CommunityForText(textField.text);
    }
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if ([string isEqualToString:@"\n"]) {
        [textField resignFirstResponder];
        if (self.CommunityForText) {
            self.CommunityForText(textField.text);
        }
        return NO;
    }
    return YES;
}


@end
